﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace y12fjydbs_1
{
    public partial class FrmYT : Form
    {
        #region 变量定义
        const int LENG_YUN = 720;
        const int NUAN_YUN = 1500;

        /// <summary>
        /// 焰条总数量
        /// </summary>
        const int cYTNum = 10;
        /// <summary>
        /// 命令发送次数
        /// </summary>
        int cCmdTimes = 0;
        MyButton[] button = new MyButton[cYTNum];
        List<YDStatus> clistYTStatus = new List<YDStatus>();

        private string NowTimeStr;
        readonly int cOffset = -100; 
        readonly int cOffset2 = -200;

        CmdType cCmdType = CmdType.None;


        public TChState[] ChState = new TChState[cYTNum];
        int[,] btnPoint = new int[10, 2] {  { 310, 290 }, { 470, 408 },  { 410, 595 },   { 210, 595 }, { 150, 408 }, 
                                            { 830, 290 }, { 990, 408 },  { 930, 595 },   { 730, 595 },  { 670, 408 }};


        private System.Timers.Timer CmdTimer = new System.Timers.Timer();
        private System.Timers.Timer CmdTimerCX = new System.Timers.Timer();

        MySerialData cSerialData;

        bool cCheckKZQStatus = false; //查询控制器状态 

        bool cIsFristRun = true;
        bool cIsFiveSecond = false;

        delegate void SetTextCallback(string text, Color TextColor);
         
        int cFireTotalSenond = (int)(0.2 * 60); //焰条总时间 2分钟 * 60秒
        #endregion

        #region 构造函数
        public FrmYT()
        {
            InitializeComponent();

            cSerialData = MyGlobal.GetSerialData();
            CmdTimer.Elapsed += OnCmdTimedEvent;
            CmdTimerCX.Elapsed += OnCmdTimedCXEvent;
            for (int i = 0; i < cYTNum; i++) button[i] = new MyButton();
            for (int i = 0; i < cYTNum; i++)
            {
                ChState[i].Status = 0;
                ChState[i].StartColor = Color.SeaShell;
                ChState[i].EndColor = Color.DimGray;
                ChState[i].Percent = 0.0f;
                ChState[i].Check = false;
                ChState[i].TotalTime = 0.0f;
            }

            MyGlobal.frmYT = this;
        } 
        #endregion

        #region FrmYT_Load
        private void FrmYT_Load(object sender, EventArgs e)
        {
            this.Text = "烟条播撒器 版本:v" + MyGlobal.Version;
            radioButton1.Enabled = false;
            radioButton2.Enabled = false;
            comboBox1.Enabled = false;

            DateTime myDateTime = DateTime.Now;
            NowTimeStr = myDateTime.ToString("    [HH:mm]   ");

            InfoDisp.AppendText("   您好，欢迎使用本系统！\n");
            InfoDisp.AppendText("   今天是" + myDateTime.ToString(" yyyy年MM月dd日, 现在是北京时间HH时mm分ss秒。\n"));

            //   richTextBox1.AppendText(NowTimeStr + "正在查询播撒控制器状态信息...\n");

            for (int i = 0; i < cYTNum; i++)
            {
                clistYTStatus.Add(new YDStatus());
                if (i < 5)
                {
                    button[i].Location = new System.Drawing.Point(btnPoint[i, 0] + 40 + cOffset, btnPoint[i, 1] - 100);
                    button[i].BtnText = string.Format("{0:d2}", i + 1);
                }
                else
                {
                    button[i].Location = new System.Drawing.Point(btnPoint[i, 0] + 40 + cOffset, btnPoint[i, 1] - 100);
                    button[i].BtnText = string.Format("{0:d2}", i - 4);
                }
                button[i].Btnsize = 100;
                button[i].Enable = true;
                button[i].BtnNo = i;
                button[i].Click += new System.EventHandler(this.btn_Click);
                Controls.Add(button[i]);
            }
            RefreshBtn();


            NowTimeStr = DateTime.Now.ToString("    [HH:mm:ss]   ");
            cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.None, CmdByte.KZQZT);
            RecviveMsg("发送 --> 焰条控制器查询指令!", Color.LightSalmon);
            cCmdType = CmdType.控制器状态;
            ReSetCmdTimer(500);
            StartFiveClock();

            ButtonEnable(false, false, false);

            GD3RBtn.Checked = true;
            GD4RBtn.Checked = false;

            comboBox1.Items.Add(1);
            comboBox1.SelectedItem = 1;
        }
        #endregion

        #region FormClosing
        private void FrmYT_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveFile();
            cSerialData.cStop = true;
            Application.Exit();
        }
        #endregion

        #region 界面时间刷新定时器
        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime myDateTime = DateTime.Now;

            NowTimeStr = myDateTime.ToString("    [HH:mm:ss]   ");
            label1.Text = myDateTime.ToString("yyyy年MM月dd日 HH时mm分ss秒");

            for (int i = 0; i < cYTNum; i++)
            {
                button[i].Validate();
                if (clistYTStatus[i].GDStatus)
                {
                    if (clistYTStatus[i].BSStatus)
                    {
                        if (clistYTStatus[i].Fireing)
                        {
                            ChState[i].Percent++;
                            button[i].BtnPercent = ChState[i].Percent / ChState[i].TotalTime;

                            if (ChState[i].Percent >= ChState[i].TotalTime)
                            {
                                clistYTStatus[i].Fireing = false;
                                ChState[i].Check = false;
                                ChState[i].Status = (int)YTStatus.不可用;
                                ChState[i].StartColor = Color.Tomato;
                                ChState[i].EndColor = Color.DarkRed;

                                button[i].Btncheck = false;
                                button[i].BtnPercent = 0;
                                button[i].BtnStartColor1 = ChState[i].StartColor;
                                button[i].BtnEndColor1 = ChState[i].EndColor;

                                RecviveMsg($"[{i+1}] 号焰条燃烧完成!", Color.LightSalmon);
                            }

                            try
                            {
                                button[i].SafeInvoke(d => d.Refresh());
                            }
                            catch (Exception ee)
                            {
                                Msg.WriteLine(ee.Message, 100, '-');
                            }
                        }
                    }
                }
            }
        }
        #endregion

        private void btn_Click(object sender, EventArgs e)
        {
            MyButton button = (MyButton)sender;

            if(button.BtnNo < 5)
            {
                if(GD3RBtn.Checked == false)
                {
                    button.BtnCheck = false;
                    return;
                }
            }
            else
            {
                if (GD4RBtn.Checked == false)
                {
                    button.BtnCheck = false;
                    return;
                }
            }
            
            if (ChState[button.BtnNo].Status != 1)
            {
                button.BtnCheck = false;
                return;
            }

            ChState[button.BtnNo].Check = button.BtnCheck;
            if (ChState[button.BtnNo].Check)
            {
                for (int i = 0; i < cYTNum; i++) if (i != button.BtnNo) ChState[i].Check = false;
                RefreshBtn();
            }

            RecviveMsg($"您选择了 [{button.BtnNo + 1}] 号焰条", Color.LightSalmon);



        }



        #region ZYContrl_Paint
 
        private void ZYContrl_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Font fnt = new Font("黑体", 30);
            Rectangle rect1 = new Rectangle(0, 0, 100, 100);
            LinearGradientBrush brh = new LinearGradientBrush(rect1, Color.Red, Color.YellowGreen, LinearGradientMode.Vertical);
            Brush brh1 = new SolidBrush(Color.White);
            g.DrawString("BF-208A飞机焰弹播撒控制系统", fnt, brh1, 469, 20);
            g.DrawString("BF-208A飞机焰弹播撒控制系统", fnt, brh, 470, 21);
            //Pen pen1 = new Pen(Color.WhiteSmoke, 2);
            Pen pen1 = new Pen(Color.Bisque, 2);
            g.DrawLine(pen1, new Point(0, 105), new Point(ClientSize.Width, 105));
            Pen pen = new Pen(Color.YellowGreen, 4);
            g.DrawLine(pen, new Point(0, 105 + 2), new Point(ClientSize.Width, 105 + 2));
            Pen pen2 = new Pen(Color.Gray, 2);
            g.DrawLine(pen2, new Point(0, 105 + 5), new Point(ClientSize.Width, 105 + 5));

            for (int i = 0; i < cYTNum; i++)
            {
                Rectangle rect = new Rectangle(btnPoint[i, 0] + 44 + cOffset, btnPoint[i, 1] - 95, 91, 91);
                if (i > 10) rect = new Rectangle(btnPoint[i, 0] + 44 + cOffset2, btnPoint[i, 1] - 95, 91, 91);
                g.DrawEllipse(pen1, rect);
                //              g.DrawEllipse(pen1, rect2);
            }
            //        Pen pen3 = new Pen(Color.WhiteSmoke, 5);
            Pen pen4 = new Pen(Color.Gray, 5);

            // Rectangle rect3 = new Rectangle(110, 150, 430, 430);
            Rectangle rect4 = new Rectangle(170+cOffset, 180, 460, 460);
            //  g.DrawEllipse(pen3, rect3);
            g.DrawEllipse(pen4, rect4);

            //  Rectangle rect5 = new Rectangle(680, 150, 430, 430);
            Rectangle rect6 = new Rectangle(790 + cOffset2, 180, 460, 460);
            //   g.DrawEllipse(pen3, rect5);
            g.DrawEllipse(pen4, rect6);

            ;

            //      Rectangle rect9 = new Rectangle(240, 280, 170, 170);
            Rectangle rect10 = new Rectangle(310+cOffset, 320, 180, 180);
            //      g.DrawEllipse(pen3, rect9);
            g.DrawEllipse(pen4, rect10);

            //     Rectangle rect11 = new Rectangle(810,280,170, 170);
            Rectangle rect12 = new Rectangle(930 + cOffset2, 320, 180, 180);
            //      g.DrawEllipse(pen3, rect11);
            g.DrawEllipse(pen4, rect12);

        }
        #endregion

        #region 左右通道切换按钮
        private void GD3RBtn_CheckedChanged(object sender, EventArgs e)
        {
            if (GD3RBtn.Checked) 
                RecviveMsg("您选择了左侧播撒器...",Color.LightSalmon);

            for (int i = 0; i < 5; i++)
            {
                if (ChState[i].Status == (int)YTStatus.可点火)
                {
                    button[i].Enable = true;

                }
                else
                {
                    //button[i].Enable = false;
                }
            }
            for (int i = 5; i < 10; i++)
            {
                //button[i].Enable = false;
                ChState[i].Check = false;
                button[i].BtnCheck = false;
            }
        }

        private void GD4RBtn_CheckedChanged(object sender, EventArgs e)
        {
            if (GD4RBtn.Checked) 
                RecviveMsg("您选择了右侧播撒器...", Color.LightSalmon);
            for (int i = 0; i < 5; i++)
            {
                //button[i].Enable = false;
                button[i].BtnCheck = false;
                ChState[i].Check = false;
            }
            for (int i = 5; i < 10; i++)
            {
                if (ChState[i].Status == (int)YTStatus.可点火)
                {
                    button[i].Enable = true;
                }
                else
                {
                    //button[i].Enable = false;
                }
            } 
        }
        #endregion




        #region 控制器状态---命令返回
        public void RecviveMsgA2(bool isReady)
        {
            if (isReady)
            {
                CmdTimer.Enabled = false;

                cIsFiveSecond = true;
                ReSetCmdTimerCX(5000);

                TbxKZQStatus.SafeInvoke(s=>s.Text = "通讯正常");
                TbxKZQStatus.SafeInvoke(s => s.BackColor = Color.Lime);

                cCheckKZQStatus = true;

                if (cIsFristRun)
                {
                    cSerialData.SendCmd_FW(CmdByte.YT, CmdByte.None);
                    cCmdType = CmdType.复位;
                    cCmdTimes = 0;
                    ReSetCmdTimer(3000);
                    RecviveMsg("发送 --> 焰条执行控制器复位指令!", Color.LightSalmon);
                    cIsFristRun = false;
                }
                else
                {
                    ButtonEnable(true, true, true);
                }

            }
            else
            {
                cIsFiveSecond = false;
                TbxKZQStatus.SafeInvoke(s => s.Text = "未通讯");
                TbxKZQStatus.SafeInvoke(s => s.BackColor = Color.DarkRed);
                ButtonEnable(false, false, false);
            }
        }
        #endregion

        #region 复位命令---命令返回
        public void RecviveMsgA7()
        {
            CmdTimer.Enabled = false;

            cSerialData.SendCmd_CX(CmdByte.YT,CmdByte.None, CmdByte.GDCS);
            cCmdTimes = 0;
            cCmdType = CmdType.挂弹状态;
            RecviveMsg("发送 --> 焰条测试结果查询指令!", Color.LightSalmon);

            for (int i = 0; i < cYTNum; i++)
            { 
                button[i].Enable = false;
                ChState[i].Status = (int)YTStatus.待测试;
                ChState[i].Check = false;
                ChState[i].StartColor = Color.SeaShell;
                ChState[i].EndColor = Color.DimGray; 
            }
            RefreshBtn();
        }
        #endregion

        #region 焰条挂弹状态返回信息A1---命令返回
        public void RecviveMsgA1(YTType ytType,List<bool> list)
        {
            cCmdType = CmdType.None;

            if (ytType == YTType.冷云)
            {
                cFireTotalSenond = LENG_YUN;
                tbxYTType.SafeInvoke(s=>s.Text = YTType.冷云.ToString());
            }
            else
            {
                cFireTotalSenond = NUAN_YUN;
                tbxYTType.SafeInvoke(s => s.Text = YTType.暖云.ToString());
            }

            for (int i = 0; i < cYTNum; i++)
            {
                clistYTStatus[i].GDStatus = list[i];
                clistYTStatus[i].Fireing = false;
                button[i].BtnCheck = false;

                ChState[i].Percent = 0;
                button[i].BtnPercent = 0;
                if (list[i])
                {
                    button[i].Enable = true;

                    ChState[i].Status = (int)YTStatus.可点火;
                    ChState[i].StartColor = Color.LightCyan;
                    ChState[i].EndColor = Color.SteelBlue;
                    ChState[i].TotalTime = cFireTotalSenond;
                }
                else
                {
                    button[i].Enable = false;
                    ChState[i].Status = (int)YTStatus.不可用;
                    ChState[i].StartColor = Color.Tomato;
                    ChState[i].EndColor = Color.DarkRed; 
                }
            }
            RefreshBtn();
            ButtonEnable(true, true, true);
        }
        #endregion

        #region 刷新焰条状态  
        private void RefreshBtn()
        {
            for (int i = 0; i < cYTNum; i++)
            {
                button[i].BtnPercent = ChState[i].Percent;
                if (button[i].Enable)
                {
                    button[i].BtnStartColor1 = ChState[i].StartColor;
                    button[i].BtnEndColor1 = ChState[i].EndColor;
                    button[i].BtnStartColor2 = Color.FromArgb(237, 99, 1);
                    button[i].BtnEndColor2 = Color.FromArgb(254, 242, 106);
                    button[i].Btncheck = ChState[i].Check;
                    button[i].SafeInvoke(d => d.Refresh());
                }
                else
                {
                    button[i].BtnStartColor1 = ChState[i].StartColor;
                    button[i].BtnEndColor1 = ChState[i].EndColor;
                    button[i].SafeInvoke(d => d.Refresh());
                }
            }
        }
        #endregion

        #region 焰条播撒返回信息A8---命令返回
        public void RecviveMsgA8(byte bsStatus, List<bool> list)
        {
            CmdTimer.Enabled = false; 

            switch (bsStatus)
            { 
                case 0xFF://已响应命令  
                    ReSetCmdTimer(cFireTotalSenond*1000 + 2000);
                    cCmdType = CmdType.查询播撒结果;
                    cCmdTimes = 0; 
                    return;
               
                case 0x0F: //播撒已完成 
                    cCmdType = CmdType.None;

                    for (int i = 0; i < cYTNum; i++)
                    {
                        if (ChState[i].Check)
                        { 
                            clistYTStatus[i].Fireing = true;
                            ChState[i].Check = false;
                            button[i].Enable = false;
                            button[i].BtnCheck = false;
                            ChState[i].StartColor = Color.LightYellow;
                            ChState[i].EndColor = Color.LightYellow;
                            button[i].BtnStartColor1 = Color.LightYellow;
                            button[i].BtnEndColor1 = Color.Yellow;
                            button[i].SafeInvoke(s => s.Refresh());
                            break;
                        }
                    }
                    break;
                //错误
                case 0x07:  
                    cCmdType = CmdType.None;
                    break;
            } 

            for (int i = 0; i < cYTNum; i++)
            {
                clistYTStatus[i].BSStatus = list[i];
                ChState[i].Check = false;
        //        button[i].BtnCheck = false; 上面的选中起作业, 这个不起作用

                if(clistYTStatus[i].GDStatus)
                {
                    if(clistYTStatus[i].BSStatus)
                    {
                        if (clistYTStatus[i].Fireing)
                        { 
                        }
                        else
                        {
                            button[i].Enable = false;
                            ChState[i].Status = (int)YTStatus.不可用;
                            ChState[i].StartColor = Color.Tomato;
                            ChState[i].EndColor = Color.DarkRed;
                        }
                    }
                    else
                    {
                        button[i].Enable = true;
                        ChState[i].Status = (int)YTStatus.可点火;
                        ChState[i].StartColor = Color.LightCyan;
                        ChState[i].EndColor = Color.SteelBlue;
                        ChState[i].TotalTime = cFireTotalSenond;
                    }
                } 
                else
                {
                    button[i].Enable = false;
                    ChState[i].Status = (int)YTStatus.不可用;
                    ChState[i].StartColor = Color.Tomato;
                    ChState[i].EndColor = Color.DarkRed;
                }
            }
            RefreshBtn(); 
            ButtonEnable(true, true, true);

        }
        #endregion

        #region 焰弹终止播撒---命令返回
        public void RecviveMsgA5()
        {
            cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.None, CmdByte.BSJG);
            RecviveMsg("左播撒器 --> 发送查询焰弹播撒结果指令!", Color.LightSalmon);

            cCmdType = CmdType.查询播撒结果;
            cCmdTimes = 0;
            ReSetCmdTimer(500);
        }
        #endregion



        #region RecviveMsg
        public void RecviveMsg(string text, Color TextColor)
        {
            if (cCmdType == CmdType.None && cbxShowFiveMsg.Checked == false && TextColor == Color.Navy)
                return;

            try
            {

                if (InfoDisp.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(RecviveMsg);
                    InfoDisp.Invoke(d, new object[] { text, TextColor });
                }
                else
                {
                    text = NowTimeStr + text + " \n";
                    InfoDisp.Focus();
                    //设置光标的位置到文本尾    
                    InfoDisp.Select(InfoDisp.TextLength, 0);
                    //滚动到控件光标处    
                    InfoDisp.SelectionFont = new Font("微软雅黑", 10.5F, FontStyle.Regular);
                    InfoDisp.SelectionColor = TextColor;
                    InfoDisp.AppendText(text);
                    InfoDisp.ScrollToCaret();
                    InfoDisp.Update();
                }
            }
            catch (Exception ee)
            {
                Msg.WriteLine(ee.Message, 100, '-');

            }
        } 
        #endregion

        #region 检查 --- 按钮
        private void BtnCheckL_Click(object sender, EventArgs e)
        {
            if (cCheckKZQStatus == false)
            {
                MessageBox.Show("通讯状态不正常!", "提示");
                return;
            }
            cSerialData.SendCmd_FW(CmdByte.YT, CmdByte.None);
            RecviveMsg("左播撒器 --> 发送控制器复位指令!", Color.LightSalmon);
            cCmdType = CmdType.复位;
            cCmdTimes = 0;
            ReSetCmdTimer(3000);



            for (int i = 0; i < cYTNum; i++)
            {
                button[i].Enable = false;
                ChState[i].Status = (int)YTStatus.待测试;
                ChState[i].Check = false;
                ChState[i].StartColor = Color.SeaShell;
                ChState[i].EndColor = Color.DimGray;
            }
            RefreshBtn();
            ButtonEnable(false, false, false);
        }
        #endregion

        #region 播撒 --- 按钮
        private void BtnFireL_Click(object sender, EventArgs e)
        {
            byte ts = 0xFA;
            
            List<bool> list = new List<bool>();

            foreach (var item in ChState)
            {
                if (item.Check)
                    list.Add(true);
                else
                    list.Add(false);
            }

            if( list.Count(s => s) != 1)
            {
                RecviveMsg(" 错误: 请选择要播撒的焰条!",Color.Red);
                return;
            }

            cSerialData.SendCmd_YTBS(CmdByte.YT,CmdByte.None,ts, list);
            RecviveMsg("发送 --> 焰条播撒指令!", Color.LightSalmon);

            cCmdType = CmdType.播撒;
            cCmdTimes = 0;
            ReSetCmdTimer(500);

            ButtonEnable(false, false, false);
        }
        #endregion

        #region 中止播撒 --- 按钮
        private void BtnStopL_Click(object sender, EventArgs e)
        {
            cSerialData.SendCmd_TZ(CmdByte.YT,CmdByte.None);
            RecviveMsg("发送 --> 中止播撒指令!", Color.LightSalmon);
            cCmdType = CmdType.中止播撒;
            cCmdTimes = 0;
            ReSetCmdTimer(500);
            ButtonEnable(false, false, false);
        }
        #endregion

        #region 手动自动切换按钮
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            comboBox1.SelectedIndex = 0;
            comboBox1.Enabled = false;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            comboBox1.Enabled = true;
        }
        #endregion
         

        #region 复位 - 命令定时器
        private void ReSetCmdTimer(int ms)
        {
            CmdTimer.Interval = ms;
            CmdTimer.AutoReset = false;
            CmdTimer.Enabled = true;
        }
        #endregion

        #region 复位 - 5s - 定时器CX
        private void ReSetCmdTimerCX(int ms)
        {
            CmdTimerCX.Interval = ms;
            CmdTimerCX.AutoReset = false;
            CmdTimerCX.Enabled = true;
        }
        #endregion

        

        #region 命令 - 定时器 - 事件
        private void OnCmdTimedEvent(Object source, ElapsedEventArgs e)
        {
            Msg.WriteLine("in FrmYT --- OnCmdTimedEvent()");
            CmdTimer.Enabled = false;

            switch (cCmdType)
            {
                case CmdType.None:
                    break;
                case CmdType.控制器状态:
                    cCmdTimes++;
                    if (cCmdTimes > 20)
                    {
                        cCmdType = CmdType.控制器状态;
                        TbxKZQStatus.Text = "未通信";
                        TbxKZQStatus.BackColor = Color.DarkRed;
                        RecviveMsg("焰条控制器 --- 初始通信测试未通过!!!", Color.Red);
                        cCmdType = CmdType.None;
                        break;
                    }  
                    cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.None, CmdByte.KZQZT);                    
                    RecviveMsg($"焰条控制器 --> 查询焰条控制器状态指令! - {cCmdTimes}", Color.LightSalmon);
                    ReSetCmdTimer(500);                 
                    break; 
                case CmdType.复位:
                    cCmdTimes++;
                    if (cCmdTimes > 2)
                    {
                        RecviveMsg("焰条控制器 --- 焰条测试未通过!!!", Color.Red);
                        cCmdType = CmdType.None;
                        break;
                    }
                    else
                    {
                        cSerialData.SendCmd_FW(CmdByte.YT, CmdByte.LEFT);
                        RecviveMsg($"焰条控制器 --> 发送焰条执行控制器复位指令! - {cCmdTimes}", Color.LightSalmon);
                        ReSetCmdTimer(3000);
                        break;
                    }
                case CmdType.挂弹状态:
                    cCmdTimes++;
                    if (cCmdTimes > 2)
                    {
                        RecviveMsg("焰条控制器 --- 焰条测试未通过!!!", Color.Red);
                        cCmdType = CmdType.None;
                        break;
                    }
                    else
                    {
                        cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.LEFT, CmdByte.GDCS);
                        RecviveMsg($"焰条控制器 --> 发送挂弹测试指令! - {cCmdTimes}", Color.LightSalmon);
                        ReSetCmdTimer(500);
                        break;
                    }
                case CmdType.播撒:
                    cCmdTimes++;
                    if (cCmdTimes > 2)
                    {
                        RecviveMsg("焰条控制器 --- 焰条播撒指令未响应!", Color.Red);
                        cCmdType = CmdType.None;
                        break;
                    }
                    else
                    {
                        cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.LEFT, CmdByte.BSJG);
                        cCmdType = CmdType.播撒;
                        ReSetCmdTimer(500);
                        RecviveMsg($"焰条控制器 --> 发送查询焰条播撒结果指令! - {cCmdTimes}", Color.LightSalmon); 
                        break;
                    }
                case CmdType.查询播撒结果:
                    cCmdTimes++;
                    if (cCmdTimes > 2)
                    {
                        RecviveMsg("焰条控制器 --- 焰条播撒结果查询失败!", Color.Red);
                        cCmdType = CmdType.None;
                        break;
                    }
                    else
                    {
                        cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.LEFT,CmdByte.BSJG);
                        RecviveMsg($"焰条控制器 --> 发送查询焰条播撒结果指令! - {cCmdTimes}", Color.LightSalmon);//A1
                        cCmdType = CmdType.查询播撒结果;
                        ReSetCmdTimer(500);
                        break;
                    }
                case CmdType.中止播撒:
                    cCmdTimes++;
                    if(cCmdTimes>2)
                    {
                        RecviveMsg("焰条控制器 --- 终止播撒指令未响应!", Color.Red);
                        cCmdType = CmdType.None;
                        ButtonEnable(true, true, true);
                    }
                    else
                    {
                        cSerialData.SendCmd_TZ(CmdByte.YT, CmdByte.LEFT);
                        RecviveMsg($"焰条控制器 --> 发送中止播撒指令! - {cCmdTimes}", Color.LightSalmon);
                        cCmdType = CmdType.中止播撒; 
                        ReSetCmdTimer(500);
                    }
                    break;
                default:
                    break;
            }
        }
        #endregion

        #region 5s - 定时器 - 事件
        private void OnCmdTimedCXEvent(Object source, ElapsedEventArgs e)
        { 
            if (cCmdType == CmdType.None)
            {
                if (cIsFiveSecond == false)
                {
                    TbxKZQStatus.SafeInvoke(s => s.Text = "未通讯");
                    TbxKZQStatus.SafeInvoke(s => s.BackColor = Color.DarkRed);
                    ButtonEnable(false, false, false);
                }

                cSerialData.SendCmd_CX(CmdByte.YT, CmdByte.None, CmdByte.KZQZT);
                if (cbxShowFiveMsg.Checked)
                {
                    RecviveMsg("焰条控制器 --> 发送查询控制器状态指令!", Color.LightSalmon);
                    Msg.WriteLine("                                                                                         焰条控制器 --- 5s定时器 cCmdType == CmdType.None!");
                }
                cIsFiveSecond = false;
            }
            else
            {
                Msg.WriteLine($"                                                                                         焰条控制器 --- 5s定时器 cCmdType = {cCmdType.ToString()}");
            }
            ReSetCmdTimerCX(5000);
        }

        #region 开启关闭-5秒-定时器 
        public void StopFiveClock()
        {
            Msg.WriteLine("关闭焰条 5秒 定时器!");
            CmdTimerCX.Enabled = false;
        }
        public void StartFiveClock()
        {
            Msg.WriteLine("开启焰条 5秒 定时器!");
            ReSetCmdTimerCX(5000);
        }
        #endregion

        #endregion  

        #region 保存日志按钮
        private void button1_Click(object sender, EventArgs e)
        { 
            SaveFile();
        }

        private void SaveFile()
        { 
            DateTime myDateTime = DateTime.Now;
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName) + "\\YT-log\\";

            if (!Directory.Exists(path)) // 如果该文件夹不存在则创建
                Directory.CreateDirectory(path);


            string FileName = path + myDateTime.ToString("yyyy年MM月dd日HH时mm分") + ".log";
            //   MessageBox.Show(FileName);
            using (StreamWriter sw = new StreamWriter(FileName))
            {
                sw.WriteLine(InfoDisp.Text);
            }
        }
        #endregion

        #region 按钮状态控制
        public void ButtonEnable(bool check, bool bs, bool stop)
        {
            BtnCheckL.SafeInvoke(s=>s.Enabled = check);
            BtnFireL.SafeInvoke(s => s.Enabled = bs);
            BtnStopL.SafeInvoke(s => s.Enabled = stop);
        }

        #endregion

        
        #region 三个主界面 - 切换按钮
        //当前就是焰条界面
        private void BtnYT_Click(object sender, EventArgs e)
        {

        }
        // 切换左烟弹界面
        private void BtnTDL_Click(object sender, EventArgs e)
        {
            StopFiveClock();

            if (MyGlobal.frmYDL == null)
            {
                MyGlobal.frmYDL = new FrmYDL();
            }
            MyGlobal.frmYDL.Show();
            MyGlobal.frmYDL.StartFiveClock();
            Hide();
        }

        private void BtnTDR_Click(object sender, EventArgs e)
        {
            StopFiveClock();
            if (MyGlobal.frmYDR == null)
            {
                MyGlobal.frmYDR = new FrmYDR();
                MyGlobal.frmYDR.Show();
                this.Hide();
            }
            else
            {
                MyGlobal.frmYDR.Show();
                MyGlobal.frmYDR.StartFiveClock();
                this.Hide();
            }


        }
        #endregion
    }
}
